# vim: set ft=make :

alias patch-gmod := fix-gmod

# Patch GMod's 64-bit beta to work properly on Linux (https://github.com/solsticegamestudios/GModPatchTool)
[group("gaming")]
fix-gmod:
    #!/usr/bin/bash
    mkdir -p /tmp/patch-gmod
    wget \
      $(curl -s https://api.github.com/repos/solsticegamestudios/GModPatchTool/releases/latest | \
      jq -r ".assets[] | select(.name | test(\"GModPatchTool-Linux.zip\")) | .browser_download_url") \
      -P /tmp/patch-gmod
    cd /tmp/patch-gmod && unzip -q GModPatchTool-Linux.zip
    chmod +x /tmp/patch-gmod/gmodpatchtool
    /tmp/patch-gmod/gmodpatchtool
    rm -rf /tmp/patch-gmod

# Kills all processes related to wine and proton. This forces it to restart next time you launch the game (you might still have to press STOP in steam to kill the game binary)
[group("gaming")]
fix-proton-hang:
    #!/usr/bin/bash
    PROTONCORE=(pv-bwrap pressure-vessel reaper explorer.exe rpcss.exe plugplay.exe services.exe svchost.exe winedevice.exe winedevice.exe wineserver)
    for PROG in "${PROTONCORE[@]}"; do
      killall -9 "$PROG"
    done

# Reset the Steam folder back to a fresh state
[group("gaming")]
fix-reset-steam:
    #!/usr/bin/bash
    source /usr/lib/ujust/ujust.sh
    STEAMPATH="$HOME/.local/share/Steam"
    # Get a list of the contents of steams top level directory except a list of folders/files we can skip to avoid losing data
    STEAMFILES=$(ls ~/.local/share/Steam/ | grep -vP "(userdata|compatibilitytools\.d|config|controller_base|steamapps|music)")
    echo "This script will ${b}remove${n} a bunch of files from $STEAMPATH and sign you out of steam!"
    echo "However your games, music, saves, controller profiles and compatibilitytools/custom-proton will not be touched."
    echo "To cancel and abort this operation press CTRL+C now, to continue press ENTER."
    read i
    killall -9 steam
    sleep 1
    echo "Resetting Steam to a freshly installed state."
    # Loop through each file and process it
    for STEAMFILE in $STEAMFILES
    do
      if [ -d "$STEAMPATH/$STEAMFILE" ]; then
        rm -rv "$STEAMPATH/$STEAMFILE"
      elif [ -f "$STEAMPATH/$STEAMFILE" ]; then
        rm -v "$STEAMPATH/$STEAMFILE"
      fi
    done
    sleep 1
    bazzite-steam &
    exit 0

# Toggle Bluetooth headset profile mode. If enabled, mic will be disabled on the Bluetooth device preventing the switch to headset profile, which has poor audio quality. Disable to restore mic functionality.
[group("audio")]
toggle-bt-mic:
    #!/usr/bin/bash
    CONFIG_FILE="/etc/wireplumber/wireplumber.conf.d/51-mitigate-annoying-profile-switch.conf"
    # Check current status
    CURRENT_STATE="Disabled"
    if [ -f "$CONFIG_FILE" ]; then
      CURRENT_STATE="Enabled"
    fi
    # Prompt user for action
    echo "Bluetooth headset profile mitigation is currently: ${bold}${CURRENT_STATE}${normal}"
    echo "Enable or Disable Bluetooth headset profile mitigation?"
    OPTION=$(ugum choose Enable Disable)
    if [[ "${OPTION,,}" == "enable" ]]; then
      echo "You chose to enable mitigation. This will disable headset mic functionality."
      echo "Requesting root privileges..."
      sudo mkdir -p "$(dirname "$CONFIG_FILE")"
      echo 'wireplumber.settings = {' | sudo tee "$CONFIG_FILE" > /dev/null
      echo '  bluetooth.autoswitch-to-headset-profile = false' | sudo tee -a "$CONFIG_FILE" > /dev/null
      echo '}' | sudo tee -a "$CONFIG_FILE" > /dev/null
      echo '' | sudo tee -a "$CONFIG_FILE" > /dev/null
      echo 'monitor.bluez.properties = {' | sudo tee -a "$CONFIG_FILE" > /dev/null
      echo '  bluez5.roles = [ a2dp_sink a2dp_source ]' | sudo tee -a "$CONFIG_FILE" > /dev/null
      echo '}' | sudo tee -a "$CONFIG_FILE" > /dev/null
      systemctl --user restart wireplumber
      echo "Mitigation has been ${green}${b}enabled${n}. Headset profile switching is now disabled."
    elif [[ "${OPTION,,}" == "disable" ]]; then
      echo "You chose to disable mitigation. This will restore headset mic functionality."
      echo "Requesting root privileges..."
      if sudo rm -f "$CONFIG_FILE"; then
        systemctl --user restart wireplumber
        echo "Mitigation has been ${red}${b}disabled${n}. Headset profile switching is now allowed."
      else
        echo "Failed to disable mitigation. Ensure you have sufficient permissions."
      fi
    else
      echo "No changes were made."
    fi

# enable or disable wake-on-lan functionality
toggle-wol ACTION="":
    #!/usr/bin/bash
    source /usr/lib/ujust/ujust.sh
    INTERFACE=$(ip link show | awk '/state UP/ {print $2}' | tr -d ':' | grep -E '^(en|eth)')
    if [[ -z "$INTERFACE" ]]; then
      echo -e "${bold}No active Ethernet interface found.${normal}"
      echo "Please ensure your Ethernet connection is enabled or connected."
      echo "Exiting without making any changes."
      exit 0
    fi
    CONFIG_FILE="/etc/udev/rules.d/81-wol.rules"
    SERVICE_FILE="/etc/systemd/system/force-wol.service"
    WOL_STATUS=$(sudo ethtool $INTERFACE | grep -P "^\s+Wake-on" | awk '{print $2}')
    CURRENT_STATE="Disabled"
    if [[ "$WOL_STATUS" == "g" ]]; then
      CURRENT_STATE="Enabled"
    fi
    OPTION="{{ ACTION }}"
    if [ "$OPTION" == "help" ]; then
      echo "Usage: ujust toggle-wol <option>"
      echo "  <option>: Specify the quick option to skip the prompt"
      echo "  Use 'enable' to enable Wake-on-LAN"
      echo "  Use 'disable' to disable Wake-on-LAN"
      echo "  Use 'force-enable' to force-enable Wake-on-LAN (persists across reboots)"
      exit 0
    elif [ -z "$OPTION" ]; then
      echo "Wake-on-LAN is currently: ${bold}${CURRENT_STATE}${normal}"
      echo "Enable, Disable Wake-on-LAN, Force-Enable, or Exit without saving?"
      echo "Note: Force-Enable will make WOL persist across reboots"
      OPTION=$(ugum choose Enable Disable Force-Enable Exit)
    fi
    if [[ "${OPTION,,}" == "enable" ]]; then
      echo "You chose to enable Wake-on-LAN."
      echo "Requesting root privileges..."
      sudo ethtool -s $INTERFACE wol g
      if ! grep -q "$INTERFACE" "$CONFIG_FILE" 2>/dev/null; then
        echo "Creating udev rule to make this setting persistent..."
        echo "ACTION==\"add\", SUBSYSTEM==\"net\", NAME==\"$INTERFACE\", RUN+=\"/usr/bin/ethtool -s \$name wol g\"" | sudo tee "$CONFIG_FILE" > /dev/null
      fi
      echo "Wake-on-LAN has been ${green}${bold}enabled${normal}."
    elif [[ "${OPTION,,}" == "disable" ]]; then
      echo "You chose to disable Wake-on-LAN."
      echo "Requesting root privileges..."
      sudo ethtool -s $INTERFACE wol d
      if [[ -f "$CONFIG_FILE" ]]; then
        echo "Removing udev rule to disable persistence..."
        sudo rm -f "$CONFIG_FILE"
      fi
      if systemctl is-enabled force-wol.service &>/dev/null; then
        sudo systemctl disable force-wol.service
        echo "Force-WOL service has been disabled."
      fi
      echo "Wake-on-LAN has been ${red}${bold}disabled${normal}."
    elif [[ "${OPTION,,}" == "force-enable" ]]; then
      echo "You chose to force-enable wake on LAN."
      echo "Requesting root privileges..."
      if [ -f "/etc/systemd/system/force-wol.service" ]; then
        echo "Removing deprecated service file"
        sudo rm "/etc/systemd/system/force-wol.service"
      fi
      sudo systemctl daemon-reload
      sudo systemctl enable --now force-wol.service
      echo "Wake on LAN force-enabled: ${green}${bold}force-wol.service${normal}"
    else
      echo "No changes were made."
    fi

# enable or disable IWD as a replacement for wpa_supplicant
[group("network")]
toggle-iwd:
    #!/usr/bin/bash
    # Explain the purpose of the script
    echo -e "This script manages enabling or disabling iwd as a replacement for wpa_supplicant for Wi-Fi networking."
    echo -e "Enabling this can improve throughput, mesh networking, and reduce latency increases when scanning for networks"
    echo -e "Disabling this can improve corporate or eduroam network compatibility"
    echo -e ""
    echo -e "WARNING: Changing this will remove all saved wifi networks"
    get_current_status() {
      if [[ -f "/etc/NetworkManager/conf.d/iwd.conf" ]]; then
        echo "Enabled"
      else
        echo "Disabled"
      fi
    }
    remove_saved_networks() {
      nmcli -t -f NAME connection show | while read -r line; do sudo nmcli connection delete "$line"; done
    }
    enable_iwd() {
      sudo mkdir -p "/etc/NetworkManager/conf.d/"
      sudo rm -f "/etc/NetworkManager/conf.d/iwd.conf"
      printf "[device]\nwifi.backend=iwd" | sudo tee /etc/NetworkManager/conf.d/iwd.conf > /dev/null
      sudo systemctl mask wpa_supplicant.service
      remove_saved_networks
      echo -e "iwd enabled. Reboot required to apply changes."
    }
    disable_iwd() {
      sudo rm -f "/etc/NetworkManager/conf.d/iwd.conf"
      sudo systemctl unmask wpa_supplicant.service
      remove_saved_networks
      echo -e "iwd disabled. Reboot required to apply changes."
    }
    # Display current status
    current_status=$(get_current_status)
    echo -e "\nCurrent iwd status: $current_status\n"
    # Prompt user for action
    CHOICE=$(ugum choose "Enable iwd" "Disable iwd" "Exit without changes")
    case "$CHOICE" in
      "Enable iwd")
        enable_iwd
        ;;
      "Disable iwd")
        disable_iwd
        ;;
      "Exit without changes")
        echo "No changes made."
        ;;
      *)
        echo "Invalid choice. Exiting without changes."
        ;;
    esac

# enable or disable a fix for 7th and 8th generation Intel chips not being able to sleep
[group("hardware")]
toggle-i915-sleep-fix:
    #!/usr/bin/bash
    # Explain the purpose of the script
    echo -e "This script manages the i915.enable_dc kernel parameter, which controls a power-saving feature for Intel graphics"
    echo -e "Enabling this setting can reduce power consumption, but may cause issues like random reboots or failed suspend on certain devices"
    echo -e "Disabling it ensures stability at the cost of slightly higher power usage"
    # Get the current i915.enable_dc setting
    get_current_status() {
      local karg_status
      karg_status=$(cat /proc/cmdline | grep -o 'i915.enable_dc=[-0-9]' | cut -d= -f2)
      if [[ -z "$karg_status" ]]; then
        echo "Not Set"
      else
        echo "$karg_status"
      fi
    }
    # Toggle i915.enable_dc kernel parameter
    update_karg() {
      local new_value=$1
      if [[ $new_value -ge 0 && $new_value -le 4 ]]; then
        echo -e "\nYou are setting power-saving mode (i915.enable_dc=$new_value).\n"
        if [[ $new_value -eq 0 ]]; then
          echo -e "This disables power-saving mode and prioritizes stability.\n"
        elif [[ $new_value -eq 1 ]]; then
          echo -e "This enables basic power-saving mode but may cause minor stability issues.\n"
        elif [[ $new_value -ge 2 ]]; then
          echo -e "This enables higher levels of power-saving mode, which may impact stability further.\n"
        fi
      elif [[ $new_value -eq -1 ]]; then
        echo -e "\nYou are setting power-saving mode to auto (i915.enable_dc=-1).\n"
      else
        echo -e "\nInvalid value for i915.enable_dc. Please choose a valid value.\n"
        return
      fi
      rpm-ostree kargs --replace "i915.enable_dc=$new_value"
      echo -e "Kernel parameter updated. Reboot required to apply changes."
    }
    # Display current status
    current_status=$(get_current_status)
    echo -e "\nCurrent i915.enable_dc setting: $current_status\n"
    # Prompt user for action
    CHOICE=$(ugum choose "Set to Auto (i915.enable_dc=-1)" "Disable Power Saving (i915.enable_dc=0)" "Set to Level 1 (i915.enable_dc=1)" "Set to Level 2 (i915.enable_dc=2)" "Set to Level 3 (i915.enable_dc=3)" "Set to Level 4 (i915.enable_dc=4)" "Unset Parameter" "Exit without changes")
    case "$CHOICE" in
      "Set to Auto (i915.enable_dc=-1)")
        echo "Setting power-saving mode to auto (i915.enable_dc=-1)..."
        update_karg -1
        ;;
      "Disable Power Saving (i915.enable_dc=0)")
        echo "Disabling power-saving mode (i915.enable_dc=0)..."
        update_karg 0
        ;;
      "Set to Level 1 (i915.enable_dc=1)")
        echo "Setting power-saving mode to level 1 (i915.enable_dc=1)..."
        update_karg 1
        ;;
      "Set to Level 2 (i915.enable_dc=2)")
        echo "Setting power-saving mode to level 2 (i915.enable_dc=2)..."
        update_karg 2
        ;;
      "Set to Level 3 (i915.enable_dc=3)")
        echo "Setting power-saving mode to level 3 (i915.enable_dc=3)..."
        update_karg 3
        ;;
      "Set to Level 4 (i915.enable_dc=4)")
        echo "Setting power-saving mode to level 4 (i915.enable_dc=4)..."
        update_karg 4
        ;;
      "Unset Parameter")
        echo "Unsetting i915.enable_dc..."
        rpm-ostree kargs --delete "i915.enable_dc=[-0-9]"
        echo -e "Kernel parameter unset. Reboot required to apply changes."
        ;;
      "Exit without changes")
        echo "No changes made."
        ;;
      *)
        echo "Invalid choice. Exiting without changes."
        ;;
    esac

# Toggle GPP0 wakeup fix to prevent unwanted system wake-ups, primarily affects Gigabyte motherboards.
[group("hardware")]
_toggle-gigabyte-wake-fix:
    #!/usr/bin/bash
    source /usr/lib/ujust/ujust.sh
    SERVICE_FILE="/etc/systemd/system/biosWakeupWorkaround.service"

    if systemctl is-enabled biosWakeupWorkaround.service &>/dev/null; then
      echo "Current status: ${green}${bold}enabled${normal}"
      CHOICE=$(ugum choose "Disable GPP0 wakeup fix" "Exit without changes")
      if [[ "$CHOICE" == "Disable GPP0 wakeup fix" ]]; then
        sudo systemctl disable --now biosWakeupWorkaround.service
        sudo rm -f "$SERVICE_FILE"
        sudo systemctl daemon-reload
        echo "GPP0 wakeup fix ${red}${bold}disabled${normal} and service file removed."
      else
        echo "No changes made."
      fi
    else
      echo "Current status: ${red}${bold}disabled${normal}"
      CHOICE=$(ugum choose "Enable GPP0 wakeup fix" "Exit without changes")
      if [[ "$CHOICE" == "Enable GPP0 wakeup fix" ]]; then
        {
          echo "[Unit]"
          echo "Description=Workaround for Gigabyte BIOS sleep/wakeup bug"
          echo ""
          echo "[Service]"
          echo "Type=oneshot"
          echo 'ExecStart=/bin/sh -c '"'"'if grep GPP0 /proc/acpi/wakeup | grep -q enabled; then echo GPP0 > /proc/acpi/wakeup; fi'"'"
          echo ""
          echo "[Install]"
          echo "WantedBy=multi-user.target"
        } | sudo tee "$SERVICE_FILE" > /dev/null
        sudo systemctl daemon-reload
        sudo systemctl enable --now biosWakeupWorkaround.service
        echo "GPP0 wakeup fix ${green}${bold}enabled${normal}."
      else
        echo "No changes made."
      fi
    fi

# Manage Steam game shortcuts on the Desktop. Usage: just steam-icons [command] (list, remove, enable, disable)
steam-icons ACTION="":
    #!/usr/bin/bash
    source /usr/lib/ujust/ujust.sh
    DESKTOP_DIR="$HOME/Desktop"
    SERVICE_NAME="steam-icons-cleanup.service"
    OPTION={{ ACTION }}
    # Function to count and list Steam shortcuts
    list_shortcuts() {
      STEAM_SHORTCUTS=()
      while IFS= read -r shortcut; do
      if grep -q "Comment=Play this game on Steam" "$shortcut" 2>/dev/null; then
        STEAM_SHORTCUTS+=("$shortcut")
      fi
      done < <(find "$DESKTOP_DIR" -name "*.desktop" -type f 2>/dev/null)
      SHORTCUT_COUNT=${#STEAM_SHORTCUTS[@]}
      if [[ $SHORTCUT_COUNT -eq 0 ]]; then
      echo "No Steam game shortcuts found on the Desktop."
      return 0
      fi
      echo -e "${b}Found $SHORTCUT_COUNT Steam game shortcuts on your Desktop:${n}"
      for shortcut in "${STEAM_SHORTCUTS[@]}"; do
      GAME_NAME=$(grep "^Name=" "$shortcut" | sed 's/^Name=//')
      echo "- $GAME_NAME"
      done
      echo ""
      return $SHORTCUT_COUNT
    }
    # Function to remove all shortcuts
    remove_all_shortcuts() {
      STEAM_SHORTCUTS=()
      while IFS= read -r shortcut; do
      if grep -q "Comment=Play this game on Steam" "$shortcut" 2>/dev/null; then
        STEAM_SHORTCUTS+=("$shortcut")
      fi
      done < <(find "$DESKTOP_DIR" -name "*.desktop" -type f 2>/dev/null)
      SHORTCUT_COUNT=${#STEAM_SHORTCUTS[@]}
      if [[ $SHORTCUT_COUNT -eq 0 ]]; then
      echo "No Steam game shortcuts found on the Desktop."
      return
      fi
      for shortcut in "${STEAM_SHORTCUTS[@]}"; do
      GAME_NAME=$(grep "^Name=" "$shortcut" | sed 's/^Name=//')
      rm -f "$shortcut"
      done
      echo -e "${green}${b}Successfully removed $SHORTCUT_COUNT Steam game shortcuts.${n}"
    }
    # Check if auto-cleanup service is enabled
    SERVICE_STATUS="disabled"
    if systemctl --user is-enabled "$SERVICE_NAME" &>/dev/null; then
      SERVICE_STATUS="enabled"
    fi
    # Process direct command arguments
    if [ "$OPTION" == "help" ]; then
      echo "Usage: just steam-icons [command]"
      echo "Commands:"
      echo "  list     - List all Steam shortcuts on Desktop"
      echo "  remove   - Remove all Steam shortcuts"
      echo "  enable   - Enable automatic cleanup on login"
      echo "  disable  - Disable automatic cleanup"
      echo "  help     - Show this help message"
      exit 0
    elif [ "$OPTION" == "list" ]; then
      list_shortcuts
      exit 0
    elif [ "$OPTION" == "remove" ]; then
      remove_all_shortcuts
      exit 0
    elif [ "$OPTION" == "enable" ]; then
      systemctl --user enable --now "$SERVICE_NAME"
      echo -e "${green}${b}Auto-cleanup enabled.${n} Steam game shortcuts will be automatically removed at login."
      exit 0
    elif [ "$OPTION" == "disable" ]; then
      systemctl --user disable --now "$SERVICE_NAME" 2>/dev/null || true
      echo -e "${red}${b}Auto-cleanup disabled.${n} Steam game shortcuts will no longer be automatically removed."
      exit 0
    fi
    # If no arguments provided or not matched, show interactive menu
    echo -e "Auto-cleanup service status: ${b}${SERVICE_STATUS}${n}\n"
    list_shortcuts
    # Ask the user what they want to do
    OPTION=$(ugum choose "Remove All Shortcuts Now" "Enable Auto-Cleanup" "Disable Auto-Cleanup" "Exit")
    case "$OPTION" in
      "Remove All Shortcuts Now")
      remove_all_shortcuts
      ;;
      "Enable Auto-Cleanup")
      systemctl --user enable --now "$SERVICE_NAME"
      echo -e "\n${green}${b}Auto-cleanup enabled.${n} Steam game shortcuts will be automatically removed at login."
      ;;
      "Disable Auto-Cleanup")
      systemctl --user disable --now "$SERVICE_NAME" 2>/dev/null || true
      echo -e "\n${red}${b}Auto-cleanup disabled.${n} Steam game shortcuts will no longer be automatically removed."
      ;;
      "Exit")
      echo "No changes were made."
      ;;
      *)
      echo "Invalid choice. Exiting without changes."
      ;;
    esac
